<template>
    <el-form label-width="100px">
        <el-form-item label="SPU 名称">{{ spuInfo.spuName }}</el-form-item>

        <el-form-item label="SKU 名称">
            <el-input placeholder="SKU 名称" v-model="skuInfo.skuName"></el-input>
        </el-form-item>

        <el-form-item label="价格(元)">
            <el-input type="number" v-model="skuInfo.price"></el-input>
        </el-form-item>

        <el-form-item label="重量(千克)">
            <el-input type="number" v-model="skuInfo.weight"></el-input>
        </el-form-item>

        <el-form-item label="规格描述">
            <el-input v-model="skuInfo.skuDesc" type="textarea" placeholder="规格描述" rows="4"></el-input>
        </el-form-item>

        <el-form-item label="平台属性">
            <!-- 遍历生成平台属性下拉框 -->
            <el-form label-width="100px" :inline="true">
                <el-form-item v-for="attr in attrList" :key="attr.id" :label="attr.attrName">
                    <el-select v-model="attr.attrIdValueId">
                        <el-option v-for="item in attr.attrValueList" :key="item.id" :label="item.valueName"
                            :value="`${item.attrId}:${item.id}`">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>

        </el-form-item>
        <el-form-item label="销售属性">
            <!-- 遍历生成销售属性下拉框 -->
            <el-form label-width="100px" :inline="true">
                <el-form-item v-for="attr in spuSaleAttrList" :key="attr.id" :label="attr.saleAttrName">
                    <el-select placeholder="请选择" v-model="attr.attrIdValueId">
                        <el-option v-for="item in attr.spuSaleAttrValueList" :key="item.id"
                            :value="`${attr.baseSaleAttrId}:${item.id}`" :label="item.saleAttrValueName" />
                    </el-select>
                </el-form-item>
            </el-form>
        </el-form-item>

        <el-form-item label="图片列表">
            <el-table :data="spuImageList" border stripe @selection-change="chooseImg">
                <el-table-column type="selection" width="55" />
                <el-table-column label="图片" width="200px">
                    <template v-slot="{ row }">
                        <el-image :src="row.imgUrl" style="width: 100px;" :lazy="true"></el-image>
                    </template>
                </el-table-column>
                <el-table-column label="名称" prop="imgName" />
                <el-table-column label="操作">
                    <template v-slot="{ row }">
                        <el-tag v-if="row.isDefault === '1'" type="primary">默认图片</el-tag>
                        <el-button v-else type="primary" @click="changeToDefault(row)">设为默认</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="save">保存</el-button>
            <el-button type="default" @click="emit('setState', 0)">取消</el-button>
        </el-form-item>
    </el-form>
</template>

<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
    name: "SkuFrom",
});
</script>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { requestSpuImgList, requestSpuSaleAttrList, type SpuImageItemType, type SpuImageListType, type SpuInfoType, type SpuSaleAttrListType } from "@/api/spu";
import { onMounted, ref } from "vue";
import { requestAttrList, type attrListType } from "@/api/attr";
import { storeToRefs } from "pinia";
import type { SkuImageListType, SkuInfoItemType } from "@/api/sku";
import useAttrStore from "@/stores/attr";
import { requestSaveSkuInfo } from "@/api/sku"

//1.接收父组件传递的自定义事件，点击取消调用，回到spuList组件
const emit = defineEmits<{
    (event: 'setState', state: number, row?: SpuInfoType): void
}>()
//2.接收父组件传递的props
const props = defineProps<{
    spuInfo: SpuInfoType
}>()
//3.拿到pinia中的category3Id
const attrStore = useAttrStore()
const { category1Id, category2Id, category3Id } = storeToRefs(attrStore)

//创建保存时要发送的数据
const skuInfo = ref<SkuInfoItemType>({
    //直接双向绑定收集的数据
    skuName: "",
    price: 0,
    weight: "",
    skuDesc: "",

    //需要从spuInfo中拿的数据
    spuId: props.spuInfo.id,
    category3Id: props.spuInfo.category3Id,

    //最后通过排他拿到的数据
    skuDefaultImg: "",

    //需要额外计算的数据
    skuImageList: [],
    skuAttrValueList: [],
    skuSaleAttrValueList: [],
})

/* //获取所有的平台属性
requestAttrList(1id,2id,3id)==>attrListType
//根据当前的spuId获取所有销售属性列表
requestSpuSaleAttrList()===>SpuSaleAttrListType
//根据当前的spuId获取所有图片列表
requestSpuImgList(spuId)===>SpuImgListType */

//定义数据保存初始化请求回来的数据
const attrList = ref<attrListType>([])
const spuSaleAttrList = ref<SpuSaleAttrListType>([])
const spuImageList = ref<SpuImageListType>([])
//4.初始化请求所有需要的数据
const getInitData = async () => {
    const promise1 = requestAttrList(category1Id.value as number, category2Id.value as number, category3Id.value as number);
    const promise2 = requestSpuSaleAttrList(props.spuInfo.id as number);
    const promise3 = requestSpuImgList(props.spuInfo.id as number);

    const result = await Promise.all([promise1, promise2, promise3])
    //把初始化请求回来的数据保存在我们创建的数据中
    attrList.value = result[0]
    spuSaleAttrList.value = result[1]
    spuImageList.value = result[2]
}
onMounted(() => {
    getInitData()
})

//点击选中的图片组成的数组的类型
interface chooseImgType {
    id: number,
    imgName: string,
    imgUrl: string,
    spuId: number,
    isDefault: string
}
//定义数据保存选中的图片
const checkedImageList = ref<SkuImageListType>([])
//5.收集点击选中的图片组成的数组
const chooseImg = (chooseImgList: chooseImgType[]) => {
    checkedImageList.value = chooseImgList
}

//6.点击切换默认图片的回调
const changeToDefault = (row: SpuImageItemType) => {
    //先清空其他的数据
    spuImageList.value.forEach((item) => {
        item.isDefault = "0"
    })
    //切换当前点击的为默认图片
    row.isDefault = "1"
}

//平台属性列表需要的数据： attrId ， valueId
//销售属性列表需要的数据： saleAttrId ， saleAttrValueId
//图片列表需要的数据： imgName ， imgUrl ，spuImgId ，isDefault
//7.保存
const save = async () => {
    //处理平台属性数据
    attrList.value.forEach((item) => {
        //判断选中的平台属性
        if (item.attrIdValueId) {
            //取出选择的平台属性对应的数据
            const [attrId, valueId] = item.attrIdValueId.split(":")
            const newAttr = {
                attrId: +attrId,
                valueId: +valueId
            }
            //插入到skuInfo的平台属性数组中
            skuInfo.value.skuAttrValueList?.push(newAttr)
        }
    })

    //处理销售属性数据
    spuSaleAttrList.value.forEach((item) => {
        //判断选中的销售属性
        if (item.attrIdValueId) {
            //取出选择的销售属性对应的数据
            const [saleAttrId, saleAttrValueId] = item.attrIdValueId.split(":")
            const newSaleAttr = {
                saleAttrId: +saleAttrId,
                saleAttrValueId: +saleAttrValueId
            }
            //插入到skuInfo的销售属性数组中
            skuInfo.value.skuSaleAttrValueList?.push(newSaleAttr)
        }
    })


    //处理图片列表数据
    checkedImageList.value.forEach((item) => {
        //把选中的图片列表数据中需要的拿出来
        const newImgInfo = {
            imgName: item.imgName,
            imgUrl: item.imgUrl,
            spuImgId: item.id,
            isDefault: item.isDefault
        }

        //添加默认图片
        if (item.isDefault === '1') {
            skuInfo.value.skuDefaultImg = item.imgUrl
        }

        //插入到skuInfo
        skuInfo.value.skuImageList?.push(newImgInfo)
    })

    //发送请求
    try {
        await requestSaveSkuInfo(skuInfo.value)
        ElMessage.success("添加成功!")
        //回到spuList
        emit('setState', 0)
    } catch (error) {
        ElMessage.error("保存失败!")
    }

}


</script>